package uk.ac.lkl.common.util.property;



import uk.ac.lkl.common.util.Property;


/**
 * An integer property optionally bounded by minimum and maximum values.
 * 
 * <p>
 * <b>Improvement:</b> The bounded nature of this class can be generified to
 * any class (that implements Comparable).
 * </p>
 * 
 * @author Darren Pearce
 * @version $Revision$
 * @version $Date$
 * 
 */
public class IntegerProperty extends Property {

	/**
     * The integer value of this property.
     * 
     */
    private int value;

    /**
     * The minimum valid value for this property.
     * 
     * If this is <code>null</code>, the minimum is ignored.
     * 
     */
    private Integer minimum;

    /**
     * The maximum valid for this property.
     * 
     * If this is <code>null</code>, the maximum is ignored.
     * 
     */
    private Integer maximum;


    /**
     * Create a new unbounded instance with the given name.
     * 
     * @param name
     *            the name of this instance
     * 
     */
    public IntegerProperty(String name) {
        this(name, null, null);
    }


    public IntegerProperty(String name, Integer minimum) {
        this(name, minimum, null);
    }


    public IntegerProperty(String name, Integer minimum, Integer maximum) {
        super(name);
        this.minimum = minimum;
        this.maximum = maximum;
    }

    public boolean doSetValue(String value) throws IllegalArgumentException {
        try {
            int newValue = Integer.parseInt(value);

            if (this.value == newValue)
                return false;

            if (minimum != null && newValue < minimum)
                throw new IllegalArgumentException("Value too low");

            if (maximum != null && newValue > maximum)
                throw new IllegalArgumentException("Value too high");

            this.value = newValue;
            return true;
        }
        catch (NumberFormatException e) {
            throw new IllegalArgumentException(e);
        }
    }


    public String getValue() {
        return Integer.toString(value);
    }


    public String getType() {
        return "Integer";
    }

}
